import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
const baseDomain = window._CONFIG["domianURL"]


// 防止token失效，弹出多个弹框
let reLogin = 0

// create an axios instance
const service = axios.create({
    // baseURL: 'http://192.168.2.224:8090/', // tdd本地
    // baseURL: 'http://192.168.2.93:8088/',  // 93
    // baseURL: 'http://192.168.2.93:8080/',  // 内网
    // baseURL: 'http://cdcxj.kmdns.net:8083/', // 外网
    baseURL: baseDomain,
    // baseURL: process.env.NODE_ENV === 'development' ? baseDomain : 'http://192.168.2.93:8080/',
    // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    withCredentials: true, // send cookies when cross-domain requests
    timeout: 0 // request timeout
})

// 响应错误处理
const err = (error) => {
    // const errMsg = error.response.data.message
    switch (error.response.status) {
        case 500:
            if (error.response.data.message === "Token失效，请重新登录") {
                reLogin++
                if (reLogin === 1) {
                    MessageBox.confirm(error.response.data.message || '您已退出登录，点击取消停留在当前页面，也可以重新登录', '登录已过期', {
                        confirmButtonText: '重新登录',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        // router.push("/login")
                        // reLogin = 0
                        store.dispatch('user/resetToken').then(() => {
                            location.reload()
                        })
                    })
                }
            } else {
                console.log(error);
                Message({
                    message: '500错误，服务端无响应',
                    type: 'error',
                    duration: 5 * 1000
                })
            }
            break;
        default:
            Message({
                message: error.response.message || error.response.data.msg || '请查看请求是否正确',
                type: 'error',
                duration: 5 * 1000
            })
            break;
    }
    return Promise.reject(error);
}

// request interceptor
service.interceptors.request.use(config => {
    // do something before request is sent
    if (store.getters.token) {
        // let each request carry token
        // ['X-Token'] is a custom headers key
        // please modify it according to the actual situation
        config.headers['X-Token'] = getToken()
    }
    return config
}, error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
})

// response interceptor
service.interceptors.response.use(response => {
    const data = response.data;
    if (!data.code) {
        // console.log('下载', response);
        // 下载
        return response;
    }

    if (data.code !== 20000) {
        Message({
            message: data.object || data.msg || (data.data && data.data.msg) || '错误',
            type: 'error',
            duration: 5 * 1000
        })

        // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
        if (data.code === 50008 || data.code === 50012 || data.code === 50014) {
            MessageBox.confirm('您已退出登录，点击取消停留在当前页面，也可以重新登录', '重新登录', {
                confirmButtonText: '重新登录',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                store.dispatch('user/resetToken').then(() => {
                    location.reload()
                })
            })
        }
        return Promise.reject(new Error(data.message || 'Error'))
    } else {
        return data
    }
}, err)

export default service
